import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/shift/current_shift_entity.dart';
import 'package:flutter_deer/database/beans/discount/discount_page_item_entity.dart';
import 'package:flutter_deer/database/beans/discount/discount_resp_entity.dart';
import 'package:flutter_deer/database/beans/discount/post_discount_count_entity.dart';
import 'package:flutter_deer/database/beans/discount/post_discount_entity.dart';
import 'package:flutter_deer/database/beans/discount/post_discount_page_list_entity.dart';
import 'package:flutter_deer/database/beans/discount/res_discount_count_entity.dart';
import 'package:flutter_deer/database/beans/employee_config.dart';
import 'package:flutter_deer/database/beans/employee_list.dart';
import 'package:flutter_deer/database/beans/get_all_goods_list.dart';
import 'package:flutter_deer/database/beans/get_user_info_entity.dart';
import 'package:flutter_deer/database/beans/list_advance_pre_pay_order_entity.dart';
import 'package:flutter_deer/database/beans/member_bean_entity.dart';
import 'package:flutter_deer/database/beans/pay/create_order_entity.dart';
import 'package:flutter_deer/database/beans/pay/pay_result_entity.dart';
import 'package:flutter_deer/database/beans/pay/post_create_qr_code.dart';
import 'package:flutter_deer/database/beans/pay_type_model.dart';
import 'package:flutter_deer/database/order_status.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/emuns/pay_type_enum.dart';
import 'package:flutter_deer/ui/cashier/bean/post_create_order.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/input_formatter/money_util.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/util/user_config_manager.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';

class CashierPageProvider extends BaseNetProvider {
  final RxDouble _totalOrderAmount = RxDouble(0);
  final Rx<DiscountItem?> mLiveDataDiscount = Rx<DiscountItem?>(null);
  final RxList<DiscountItem> mCardList = <DiscountItem>[].obs;
  final RxDouble offLineDiscount = RxDouble(0);
  final int _offLineSwitch = 1;
  final Rx<EmployeeEntity?> mSelectEmployee = Rx<EmployeeEntity?>(null);
  final List<EmployeeEntity> mSelectListEmployee = <EmployeeEntity>[];
  final List<EmployeeEntity> mAllListEmployee = <EmployeeEntity>[];
  final RxBool employeeConfigOilRx = RxBool(false);
  final RxBool employeeConfigAtWillRx = RxBool(false);
  final RxBool employeeConfigStoredRx = RxBool(false);
  final Rx<MemberBeanMembers?> _members = Rx<MemberBeanMembers?>(null);
  final RxList<AppOrderBean> _selectListOils = <AppOrderBean>[].obs;
  final RxList<GetAllGoodsList> _selectListGoods = <GetAllGoodsList>[].obs;
  final RxString orderStatus = RxString('');
  String orderPollFinanceId = '';
  final RxString orderMqttId = RxString('');
  final RxString advanceOrderCount = RxString('');
  final RxList<PayTypeModel> mALlListPayType = <PayTypeModel>[].obs;

  // 获取总金额
  double get totalOrderAmountRx => _totalOrderAmount.value;

  // 获取活动优惠数据
  DiscountItem? get getCurrentDiscount => mLiveDataDiscount.value;

  RxBool isExpanded = false.obs;

  // 获取线下优惠开关
  int get offLineSwitch => _offLineSwitch;

  // 获取会员信息
  MemberBeanMembers? get memberInfo => _members.value;

  // 获取优惠信息
  String get mDiscountTotalTextRx => getDiscountText();

  // 选择的油品
  RxList<AppOrderBean> get selectListOils => _selectListOils;

  // 选择的商品
  RxList<GetAllGoodsList> get selectListGoods => _selectListGoods;

  // 选择的支付方式
  PayTypeModel? _mPayType;

  // Rx的支付方式
  Rx<PayTypeModel?> mPayTypeRx = Rx<PayTypeModel?>(null);

  // 选择的优惠券
  RxList<CouponBean> selectedCoupon = <CouponBean>[].obs;

  // 优惠券的限制
  Rx<ResDiscountCountEntity> couponLimit = ResDiscountCountEntity().obs;

  // 设置支付方式
  void selectPayType(PayTypeModel? payType) {
    _mPayType = payType;
    mPayTypeRx.value = payType;
    if (payType != null && payType.paymentCode != PayTypeEnum.Card.paymentCode) {
      refreshDiscount();
    }
  }

  // 赋值优惠信息
  void setDiscountInfo(DiscountItem? info) {
    mLiveDataDiscount.value = info;
  }

  // 判断已选的油单是否是第一个
  bool isFirstOil(AppOrderBean bean) {
    return _selectListOils.isNotEmpty && _selectListOils[0].energyOrderId == bean.energyOrderId;
  }

  // 判断已选的油单是否是第二个
  bool isSecondOil(AppOrderBean bean) {
    return _selectListOils.isNotEmpty && _selectListOils.length >= 2 && _selectListOils[1].energyOrderId == bean.energyOrderId;
  }

  // 判断是否已经选了两个油单
  bool isSelectedTwoOil() {
    return _selectListOils.length >= 2;
  }

  // 判断是否是纯便利店
  bool isOnlyStore() {
    return _selectListOils.isEmpty;
  }

  // 获取支付按钮文本
  String getPayText() {
    if (mPayTypeRx.value == null) {
      return '请选择支付方式';
    }
    return mPayTypeRx.value?.paymentName ?? '';
  }

  // 退出用户
  void logout() {
    _members.value = null;
    // 清空优惠
    clearDiscount();
    refreshDiscount();
  }

  // 获取活动优惠文本
  String getDiscountText() {
    if (_members.value == null) {
      return '登录后享受';
    }
    // print('---1> ${_mLiveDataDiscount}');
    // print('---2> ${_mLiveDataDiscount.value}');
    // print('---3> ${_mLiveDataDiscount.value?.discounts}');
    // print('---3> ${_mLiveDataDiscount.value?.discounts.isEmpty == true}');
    // print('---3> ${_mLiveDataDiscount.value?.discounts.isNotEmpty == true}');
    if (getCurrentDiscount?.discounts.isNotEmpty != true) {
      return '暂无活动优惠';
    }
    return '￥${getCurrentDiscount?.discounts.fold('0.0', (sum, item) => sum.minus(item.discountAmount?.formatYuan ?? '0.0'))}';
  }

  // 获取积分抵现文本
  MapEntry<String, Color> getIntegralDiscountText() {
    final discountInfo = getCurrentDiscount?.integralToCashDiscount;

    print('object: $discountInfo');

    if (discountInfo?.available == true && discountInfo?.discountAmount?.isNotEmpty != true) {
      return const MapEntry('未使用', Colours.grey0A0A0A);
    }

    if (discountInfo?.available != true) {
      final str = discountInfo?.reason?.isEmpty == true ? '无可用积分' : discountInfo?.reason ?? '无可用积分';
      return MapEntry(str, Colours.grey0A0A0A);
    }

    final amount = discountInfo?.discountAmount ?? 0;
    return MapEntry('￥$amount', Colours.red);
  }

  // 获取商家优惠券文本
  MapEntry<String, Color> getCouponText() {
    if (_members.value == null) {
      return const MapEntry('登录后享受', Colours.grey0A0A0A);
    }
    final discount = getCurrentDiscount;
    if (discount != null && discount.couponList?.isNotEmpty == true) {
      final amount = discount.couponDiscountAmount;
      if (amount.toDouble >= 0) {
        return MapEntry('-￥$amount', Colours.red);
      }
    }
    final couponCount = getCurrentDiscount?.couponCount;
    if (couponCount == null) {
      return const MapEntry('暂无优惠券', Colours.grey0A0A0A);
    }
    if (couponCount == 0) {
      return const MapEntry('暂无优惠券', Colours.grey0A0A0A);
    }
    if (couponCount > 10) {
      return const MapEntry('10+张优惠券可用', Colours.grey0A0A0A);
    }
    return MapEntry('$couponCount张优惠券可用', Colours.grey0A0A0A);
  }

  // 选卡
  void selectCard(DiscountItem item) {
    setDiscountInfo(item);
  }

  // 判断是否选中了卡
  RxBool isSelectedCard(DiscountItem item) {
    return (getCurrentDiscount?.showCardNo == item.showCardNo && item.showCardNo.isNotEmpty).obs;
  }

  // 这里要实现局部刷新
  // 1、是否上传
  // 2、价格异常
  // 3、选择状态，支付状态
  // 点击选择的商品
  void selectOilItem(AppOrderBean item, {bool clear = false}) {
    // 取消
    if (_selectListOils.contains(item)) {
      if (clear) {
        _selectListOils.clear();
      } else {
        _selectListOils.remove(item);
      }
      print('[remove select]: ${item.toStringOrder()}');
    } else {
      _selectListOils.clear();
      _selectListOils.add(item);
      print('[add select]: ${item.toStringOrder()}');
    }
  }

  // 点击新增选择的商品
  void selectGoods(List<GetAllGoodsList> goods) {
    _selectListGoods.value = goods;
  }

  // 移除商品
  void removeGoods(GetAllGoodsList goods) {
    print('移除商品: ${goods.goodsName} ---> ${_selectListGoods.length}');
    goods.count.value = 1;
    _selectListGoods.value.removeWhere((element) => element.goodsId == goods.goodsId);
    _selectListGoods.refresh();
    print('移除商品后: ${_selectListGoods.length}');
  }

  // 计算总优惠
  String calculateTotalDiscount() {
    return '${_totalOrderAmount.value}'.minus(getCurrentDiscount?.discountAmount ?? '0.00').minus('${offLineDiscount.value}');
  }

  // 计算线下优惠最大值
  String getMaxOffLineDiscount() {
    return '${_totalOrderAmount.value}'.minus(getCurrentDiscount?.discountAmount ?? '0.00');
  }

  /// 根据手机号请求会员信息
  void requestMemberInfo({String? phone, String? cardNo, String? uuId, void Function()? onGiftCard}) {
    final Map<String, String> params = <String, String>{};
    params['businessType'] = 'LOGIN';
    params['phone'] = phone ?? '';
    params['encryptedStr'] = cardNo ?? '';
    params['cardId'] = uuId ?? '';
    // params['plateNo'] = '';
    // params['memberCode'] = '';
    asyncRequestNetwork<MemberBeanEntity>(
      Method.get,
      url: HttpApi.getMember,
      queryParameters: params,
      onSuccess: (data) {

        // 如果是礼品卡
        if (data?.memberAccount != null && data?.memberAccount is Map<String, dynamic>) {
          final map = data?.memberAccount as Map<String, dynamic>;
          _members.value = null;
          mLiveDataDiscount.value = DiscountItem()
            ..memberAccountId = '${map['id']}';
          // print('礼品卡: ${data?.memberAccount.runtimeType}');
          selectPayType(mALlListPayType.firstWhereOrNull((e) => e.paymentCode == PayTypeEnum.Card.paymentCode));
          onGiftCard?.call();
          return;
        }

        if (data?.members?.isNotEmpty != true) {
          Toast.show('会员不存在');
          return;
        }

        if ((data?.members?.length ?? 0) > 1) {
          showSelectList(data?.members ?? []);
        } else {
          _members.value = data?.members?.firstOrNull;
        }
      },
    );
  }

  // 展示多选列表
// 展示多选列表
  void showSelectList(List<MemberBeanMembers> members) {
    Get.dialog<void>(AlertDialog(
      title: const Text('选择会员'),
      content: SizedBox(
        width: 300,
        height: 300,
        child: ListView.builder(
          itemCount: members.length,
          itemBuilder: (context, index) {
            final member = members[index];
            return Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () {
                  _members.value = member;
                  Get.back<void>(); // 关闭对话框
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  decoration: const BoxDecoration(
                      border: Border(
                    bottom: BorderSide(color: Colors.grey, width: 0.5),
                  )),
                  child: Row(
                    children: [
                      // 显示会员姓名
                      Text('${member.phone?.phone}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
                      const SizedBox(width: 10),
                      // 显示会员手机号（如果存在）
                      Text('${member.nickname}', style: const TextStyle(fontSize: 14, color: Colors.grey)),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    ));
  }

  // 判断是否可以点击支付方式
  bool canClickPayType() {
    return _selectListOils.isNotEmpty || _selectListGoods.isNotEmpty;
  }

  // 获取油品总金额
  String getOilTotalAmount() {
    String totalAmount = '0.00';
    for (var oil in _selectListOils) {
      totalAmount = totalAmount.plus(oil.mny.toYuan);
    }
    return totalAmount;
  }

  // 获取油品总升数
  String getOilTotalVol() {
    int totalVol = 0;
    for (var oil in _selectListOils) {
      totalVol = totalVol + oil.vol;
    }
    return totalVol.toYuan;
  }

  // 获取最终去掉优惠之后的金额 - 线下优惠
  String getFinalAmount() {
    return '${_totalOrderAmount.value}'.minus(getCurrentDiscount?.discountAmount ?? '0.00').minus('${offLineDiscount.value ?? '0.00'}');
  }

  // 获取优惠参数
  PostDiscountEntity makePostDiscountEntity() {
    final PostDiscountEntity postDiscountEntity = PostDiscountEntity();
    final AppOrderBean? order = _selectListOils.firstOrNull;
    if (order != null) {
      postDiscountEntity.energyCategoryId = order.categoryId;
      postDiscountEntity.energyGoodsId = order.mchGoodsId;
      postDiscountEntity.price = order.prc.toYuan;
    }
    //获取当前的会员信息id，如果有礼品卡就是空的
    postDiscountEntity.mchMemberId = _members.value?.mchMemberId;
    //加油卡id，也可能是礼品卡id
    postDiscountEntity.memberAccountId = '${getCurrentDiscount?.memberAccountId}';
    postDiscountEntity.orderAmount = getOilTotalAmount();
    postDiscountEntity.quantity = getOilTotalVol();
    // useCoupon
    postDiscountEntity.useCoupon = selectedCoupon.isNotEmpty;

    //支付方式
    postDiscountEntity.payType = _mPayType?.getPayTypeDiscount();
    postDiscountEntity.couponList = selectedCoupon
        .map((e) => Coupon()
          ..couponNum = e.couponUseNum
          ..mchCouponId = e.mchCouponId ?? ''
          ..memberCouponId = e.memberCouponId ?? '')
        .toList();

    postDiscountEntity.couponSelectType = getCurrentDiscount?.couponSelectType;

    // 商品
    postDiscountEntity.storeGoodsInfos = _getGoodsInfos();
    // 积分
    postDiscountEntity.useIntegral = getCurrentDiscount?.integralToCashDiscount?.useIntegral;

    // 打印出基本信息
    print('请求优惠：${postDiscountEntity.toBaseString()}');
    return postDiscountEntity;
  }

  // 获取支付参数
  CreateOrderEntity makeOrderPayParams({String? qrCode, String? psw}) {
    final CreateOrderEntity mPay = CreateOrderEntity();

    // 优惠券填装数据
    mPay.discountAmount = getCurrentDiscount?.discountAmount ?? '';
    mPay.couponSelectType = getCurrentDiscount?.couponSelectType;

    final List<Discount> discounts = [];

    // 商户优惠券
    if (getCurrentDiscount?.couponList != null) {
      for (final value in getCurrentDiscount!.couponList!) {
        discounts.add(Discount()
          ..discountAmount = value.couponAmount ?? ''
          ..discountDesc = value.couponName ?? ''
          ..memberCouponId = value.couponId ?? ''
          ..discountType = 'coupon');
      }
    }
    mPay.useCoupon = discounts.isNotEmpty;

    // 活动优惠
    if (getCurrentDiscount?.discounts != null) {
      for (final value in getCurrentDiscount!.discounts!) {
        discounts.add(Discount()
          ..memberCouponId = getCurrentDiscount?.couponId ?? ''
          ..discountAmount = value.discountAmount
          ..discountBizId = value.promotionsId
          ..discountDesc = value.discountDesc
          ..discountType = value.discountType
          ..exclusiveStatus = value.exclusiveStatus);
      }
    }

    // 积分抵现
    final integralToCash = getCurrentDiscount?.integralToCashDiscount;
    if (integralToCash != null) {
      discounts.add(Discount()
        ..discountAmount = integralToCash.discountAmount ?? ''
        ..discountDesc = integralToCash.typeDesc ?? ''
        ..discountType = 'integralToCash'
        ..discountBizId = integralToCash.promotionsId ?? ''
        ..useIntegral = integralToCash.useIntegral ?? '');
      // 积分抵扣
      mPay.useIntegral = integralToCash.useIntegral;
      mPay.useIntegralToCash = true;
    }

    mPay.discounts = discounts;

    // 离线优惠
    if (offLineDiscount.value > 0.0) {
      mPay.offlineDiscounts = CreateOrderOfflineDiscounts()
        ..offlineDiscountsAmount = '${offLineDiscount.value}'
        ..promotionsMode = 1;
      mPay.offlineDiscountsAmount = '${offLineDiscount.value}';
    }

    // 油品
    final AppOrderBean? order = _selectListOils.firstOrNull;
    if (order != null) {
      mPay.energyGoods = EnergyGoods()
        ..goodsAmount = getOilTotalAmount()
        ..quantity = getOilTotalVol()
        ..price = order.prc.toYuan ?? ''
        ..mchGoodsId = order.mchGoodsId ?? ''
        ..shelfId = order.shelfId ?? ''
        ..shelfNo = '${order.nzl}';
    }
    // 油单ids
    mPay.energyOrderIds = _selectListOils.map((e) => e.energyOrderId).where((element) => element != null).toList();

    // 会员 当前的会员信息id，如果有礼品卡就是空的
    mPay.mchMemberId = _members.value?.mchMemberId ?? '';
    // mPay.memberPlateNo = _members?.memberPlates?.firstOrNull?.plateNo;

    // 支付信息
    mPay.payInfo = PayInfo()
          ..accountType = getCurrentDiscount?.memberAccountType
          ..memberAccountId = getCurrentDiscount?.memberAccountId //如果是会员卡就是卡id，也可能是礼品卡id
          ..payAmount = getFinalAmount()
          ..payType = _mPayType?.paymentCode
          ..payMethod = _mPayType?.getOrderPayType()
          ..authCode = qrCode
          ..password = psw?.toMd5 ?? ''
          ..payOrderId = ''
        // ..thirdDouYCouponRequests = '' //抖音券
        ;
    mPay.douYinPay = false;

    // 员工
    mPay.staffId = mSelectEmployee.value?.userId ?? '';
    mPay.staffName = mSelectEmployee.value?.userName ?? '';

    // 便利店商品 _selectListGoods转为StoreGoodsInfos
    mPay.storeGoodsInfos = _getGoodsInfos();

    // print('请求支付：${mPay.toBaseString()}');
    return mPay;
  }

  // 便利店商品 _selectListGoods转为StoreGoodsInfos
  List<StoreGoodsInfos> _getGoodsInfos() {
    final goodsInfos = _selectListGoods
        .map((e) => StoreGoodsInfos()
          ..price = '${e.price}'
          ..quantity = e.count.value
          ..mchGoodsId = e.goodsId
          ..goodsAmount = e.getTotalPrice().toYuan
          ..salesChannelGoodsId = e.salesChannelGoodsId)
        .toList();
    return goodsInfos;
  }

  // 计算当前券是否可以叠加
  bool canStillOverlay(CouponBean coupon, {String tag = 'canStillOverlay'}) {
    if (selectedCoupon.contains(coupon)) {
      print('[$tag] $coupon 优惠券已选择');
      return false;
    }
    if (!selectedCoupon.isNotEmpty) {
      print('[$tag] $coupon 优惠券未选择');
      return false;
    }

    // 1、数目限制
    if (couponLimit.value.couponOverlayLimit == _getSelectOilCouponUseNum()) {
      print('[$tag] $coupon 能源券最多使用${couponLimit.value.couponOverlayLimit}张');
      return false;
    }

    // selectedCoupon转为新的列表
    final List<CouponBean> newSelectedCoupon = List.from(selectedCoupon);

    if (couponLimit.value.storeGoodsCouponConfig != 1) {
      if (coupon.isGoodsCoupon && newSelectedCoupon.any((element) => element.isOilCoupon)) {
        print('[$tag] $coupon 便利店券和能量券不能同时使用');
        return false;
      }
      if (coupon.isOilCoupon && newSelectedCoupon.any((element) => element.isGoodsCoupon)) {
        print('[$tag] $coupon 便利店券和能量券不能同时使用');
        return false;
      }
    }

    if (couponLimit.value.storeGoodsCouponConfig == 1) {
      if (newSelectedCoupon.any((element) => element.isGoodsCoupon)) {
        print('[$tag] $coupon 便利店券只能使用一张');
        return false;
      }
    }

    if (coupon.isOilCoupon && coupon.canOverlayOther != true) {
      print('[$tag] $coupon 存在非叠加券');
      return false;
    }

    if (newSelectedCoupon.any((element) => element.isOilCoupon && element.canOverlayOther == true && element.superpositionLimit == 1)) {
      if (coupon.superpositionLimit == 0) {
        print('[$tag] $coupon 券可叠加但是存在不支持活动优惠');
        return false;
      }
    }
    if (newSelectedCoupon.any((element) => element.isOilCoupon && element.canOverlayOther == true && element.superpositionLimit == 0)) {
      if (coupon.superpositionLimit == 1) {
        print('[$tag] $coupon 券可叠加但是存在不支持活动优惠');
        return false;
      }
    }
    return true;
  }

  // 计算当前券的最大可用数目
  int getMaxCouponNum(CouponBean coupon) {
    if (selectedCoupon.contains(coupon)) {
      final limit1 = coupon.overlayLimit ?? 0;
      final totalLimit = couponLimit.value.couponOverlayLimit ?? 0;
      final useNum = coupon.couponUseNum!;

      int otherUseNum = 0;
      for (final mCoupon in selectedCoupon) {
        if (mCoupon.isOilCoupon && mCoupon != coupon) {
          otherUseNum = otherUseNum + (mCoupon.couponUseNum!);
        }
      }

      final limit2 = totalLimit - otherUseNum;

      final result = min(limit1, limit2);
      print('[${coupon}] '
          '\n\t\t\t\t单券可用：$result '
          '\n\t\t\t\t单券限制：$useNum / $limit1 '
          '\n\t\t\t\t总券限制：($totalLimit-$otherUseNum)  '
          '\n\t\t\t\t别的已选：$otherUseNum');
      return result;
    }
    return 0;
  }

  // 计算已经选择的油品券的使用数量
  int _getSelectOilCouponUseNum() {
    int count = 0;
    for (final coupon in selectedCoupon) {
      if (coupon.isOilCoupon) {
        count = count + (coupon.couponUseNum!);
      }
    }
    return count;
  }

  /// 计算优惠
  void refreshDiscount({bool clearSelect = false, void Function(List<DiscountItem>)? successCallback}) {
    if (!canClickPayType()) {
      return;
    }

    if (_mPayType == null) {
      return;
    }

    if (clearSelect) {
      selectedCoupon.clear();
    }

    asyncRequestNetwork<List<DiscountItem>>(
      Method.post,
      url: HttpApi.getDiscount,
      params: makePostDiscountEntity().toJson(),
      onSuccess: (data) {
        final first = data?.firstOrNull;

        setDiscountInfo(data?.firstOrNull);

        successCallback?.call(data ?? []);

        // 如果是加油卡支付
        if (_mPayType?.paymentCode == PayTypeEnum.Card.paymentCode) {
          // mCardList 替换其中的元素
          final index = mCardList.indexWhere((element) => element.memberAccountId == first?.memberAccountId);
          if (index != -1) {
            mCardList[index] = first!;
            // mCardList.refresh();
          }
        }

        // 提示不可用原因
        final couponNotUseDesc2 = first?.couponNotUseDesc ?? '';
        if (couponNotUseDesc2.isNotEmpty) {
          selectedCoupon.clear();
          Toast.show(couponNotUseDesc2);
        }
      },
    );
  }

  /// 订单支付
  void orderPay({
    String? qrCode,
    String? psw,
    required void Function(PayResultEntity? data, String successInfo) onSuccess,
    required void Function(String msg) onError,
  }) {
    if (!canClickPayType()) {
      Toast.show('请先选商品');
      return;
    }
    orderStatus.value = '';
    final orderEntity = makeOrderPayParams(qrCode: qrCode, psw: psw);
    if (qrCode?.isNotEmpty ?? false) {
      orderStatus.value = '已扫描${qrCode?.payType ?? ''}二维码';
    }
    asyncRequestNetwork<PayResultEntity>(
      Method.post,
      url: HttpApi.createOrderV1,
      params: orderEntity.toJson(),
      onSuccess: (data) {
        final orderDes = '[${OrderPayStatus.getDesc(data?.payResult?.payStatus)}] ${data?.payResult?.failReason}';
        if (data?.payResult?.success ?? false) {
          onSuccess(data, orderDes);
        } else {
          onError(orderDes);
        }
        orderStatus.value = orderDes;
      },
      onError: (code, msg) {
        onError('[支付失败] code:$code msg"$msg');
        orderStatus.value = '[支付失败] code:$code msg:"$msg';
      },
    );
  }

  /// 轮询订单状态
  void pollOrderStatus({
    required void Function() onSuccess,
    required void Function(String msg) onError,
  }) {
    if (orderPollFinanceId.isEmpty) {
      return;
    }
    asyncRequestNetwork<PayResultPayResponse>(
      Method.get,
      url: '${HttpApi.pollOrderStatus}$orderPollFinanceId',
      onSuccess: (data) {
        if (orderPollFinanceId.isEmpty) {
          return;
        }
        final orderDes = '[${OrderPayStatus.getDesc(data?.payStatus)}] ${data?.failReason}';
        orderStatus.value = orderDes;
        switch (data?.payStatus) {
          case OrderPayStatus.SUCCESS_PAY:
            onSuccess();
            break;
          case OrderPayStatus.FAIL_PAY:
          case OrderPayStatus.CANCEL_PAY:
            onError(orderDes);
            break;
          case OrderPayStatus.UNPAID_PAY:
          case OrderPayStatus.PAYING_PAY:
            // 继续下一次轮询（3秒后）
            Future.delayed(const Duration(seconds: 3), () {
              pollOrderStatus(
                onSuccess: onSuccess,
                onError: onError,
              );
            });
            break;
          default:
            onError(orderDes);
        }
      },
      onError: (code, msg) {
        onError(msg);
        orderStatus.value = '[查询失败] code:$code msg:"$msg';
      },
    );
  }

  /// 弃单 giveUpOrder
  void giveUpOrder(
    AppOrderBean item,
    int code, {
    required String reason,
    required void Function(String msg) onSuccess,
    required void Function(String msg) onError,
  }) {
    asyncRequestNetwork<String>(
      Method.post,
      url: HttpApi.giveUpOrder,
      params: {
        'code': code, //弃单类型：2020回罐|2030数据错误
        'energyOrderIds': [item.energyOrderId],
        'reason': reason,
      },
      onSuccess: (data) {
        AppOrderBean.updateOrderStatusByCode(item.energyOrderCode, code);
        onSuccess(data ?? '');
      },
      onError: (code, msg) {
        onError(msg);
      },
    );
  }

  /// 获取会员优惠券数量
  void getMemberCouponCount({
    required void Function() success,
  }) {

    if (_members.value == null) {
      return;
    }
    if (_mPayType == null) {
      return;
    }
    if (!canClickPayType()) {
      return;
    }

    final AppOrderBean? order = _selectListOils.firstOrNull;
    final param = PostDiscountCountEntity()
      ..mchMemberId = _members.value?.mchMemberId ?? ''
      ..memberAccountId = getCurrentDiscount?.memberAccountId //todo 如果是会员卡就是卡id，也可能是礼品卡id
      ..energyCategoryId = order?.categoryId ?? ''
      ..energyGoodsId = order?.mchGoodsId ?? ''
      ..goodsAmount = getOilTotalAmount()
      ..goodsPrice = order?.prc.toYuan ?? ''
      ..quantity = getOilTotalVol()
      ..storeGoodsInfos = _getGoodsInfos()
      ..payType = _mPayType?.paymentCode
      ..payMethod = _mPayType?.getOrderPayType()
      ..canUseStoreCoupon = getCurrentDiscount?.canUseStoreCoupon;

    asyncRequestNetwork<ResDiscountCountEntity>(
      Method.post,
      url: HttpApi.getMemberCouponCount,
      params: param.toJson(),
      onSuccess: (data) {
        couponLimit.value = data ?? ResDiscountCountEntity();
        success();
      },
    );
  }

  /// 获取会员优惠券列表
  void getMemberCouponList({
    required void Function(List<CouponBean>?) success,
  }) {
    final AppOrderBean? order = _selectListOils.firstOrNull;
    final param = PostDiscountPageListEntity()
      ..mchMemberId = _members.value?.mchMemberId ?? ''
      //获取当前的账户id，如果是会员卡就是卡id，也可能是礼品卡id
      ..memberAccountId = getCurrentDiscount?.memberAccountId
      ..available = true
      ..energyGoodsId = order?.mchGoodsId ?? ''
      ..goodsAmount = getOilTotalAmount()
      ..goodsPrice = order?.prc.toYuan ?? ''
      ..storeGoodsInfos = _getGoodsInfos()
      ..quantity = getOilTotalVol()
      ..payType = _mPayType?.paymentCode
      ..payMethod = _mPayType?.getOrderPayType()
      ..pageSize = '100'
      ..lastRowNum = '0'
      ..canUseStoreCoupon = getCurrentDiscount?.canUseStoreCoupon
      ..selectCouponIds = getCurrentDiscount?.couponList.map((e) => e.couponId ?? '').whereType<String>().toList();

    asyncRequestNetwork<CouponBeanList>(
      Method.post,
      url: HttpApi.getMemberCouponList,
      params: param.toJson(),
      onSuccess: (data) {
        success(data?.list);
      },
    );
  }

  /// 获取员工绩效配置
  void getEmployeeConfig({void Function(bool)? success}) {
    asyncRequestNetwork<List<EmployeeConfig>>(
      isShow: false,
      Method.get,
      url: HttpApi.getPerformanceConfig,
      onSuccess: (list) {
        bool isSuccess = false;
        list?.forEach((it) {
          if (it.key == 'EMPLOYEE_PERFORMANCE_ENERGY') {
            isSuccess = true;
            EmployeeConfig.saveEmployeeConfigEnergy(it.open && it.pos);
            employeeConfigOilRx.value = it.open && it.pos;
          }
          if (it.key == 'EMPLOYEE_PERFORMANCE_STORED') {
            isSuccess = true;
            EmployeeConfig.saveEmployeeConfigStored(it.open && it.pos);
            employeeConfigStoredRx.value = it.open && it.pos;
          }
          if (it.key == 'EMPLOYEE_AT_WILL') {
            isSuccess = true;
            EmployeeConfig.saveEmployeeConfigAtWill(it.open);
            employeeConfigAtWillRx.value = it.open;
          }
        });
        success?.call(isSuccess);
      },
    );
  }

  /// 计算生成二维码
  void calculateQrCode({required void Function(String msg) onSuccessCallBack}) {
    if (isOnlyStore()) {
      onSuccessCallBack('');
      return;
    }
    final param = PostCreateQrCode();
    final gunByNzl = UserConfigManager.getGunByNzl(_selectListOils.firstOrNull?.nzl ?? 0);
    final qrCodeJsonData = QrCodeJsonData()
          ..mchGoodsId = _selectListOils.firstOrNull?.mchGoodsId
          ..goodsShortName = _selectListOils.firstOrNull?.mchGoodsName
          ..price = _selectListOils.firstOrNull?.prc.toYuan
          ..shelfId = _selectListOils.firstOrNull?.shelfId
          ..categoryId = _selectListOils.firstOrNull?.categoryId
          ..shelfNo = _selectListOils.firstOrNull?.nzl.toString()
          ..shelfName = gunByNzl?.shelfName
          ..unitName = _selectListOils.firstOrNull?.unitName
          ..goodsAmount = getOilTotalAmount()
          ..mchUserId = mSelectEmployee.value?.userId
          ..mchUserName = mSelectEmployee.value?.userName
          ..energyOrderIds = _selectListOils.map((e) => e.energyOrderId).toList()
          ..storeGoodsInfos = _getGoodsInfos()
        //..mobilePayId = _selectListOils.firstOrNull?.mobilePayId
        ;
    param.extFields = qrCodeJsonData.toJson().toString();
    asyncRequestNetwork<String>(
      Method.post,
      url: HttpApi.generateQrCode,
      params: param.toJson(),
      onSuccess: (data) {
        onSuccessCallBack(data ?? '');
        print('生成二维码---> $data');
      },
    );
  }

  @override
  void onInit() {
    super.onInit();
    // 监听油品列表变化
    _selectListOils.listen((_) {
      calculateTotalOrderAmount(tag: 'oil--change');
    });

    // 监听商品列表变化
    _selectListGoods.listen((_) {
      calculateTotalOrderAmount(tag: 'goods--change');
    });

    // 初始化员工
    if (mSelectEmployee.value == null) {
      final user = GetUserInfoEntity.get();
      mSelectEmployee.value = EmployeeEntity()
        ..admin = user?.admin ?? 0
        ..userName = user?.name ?? ''
        ..userId = user?.merchantUserId ?? '';
    }
  }

  void calculateTotalOrderAmount({String tag = ''}) {
    print('计算总金额---> [$tag]');
    double total = 0.0;

    // 计算油品总金额
    for (final oil in _selectListOils) {
      total += oil.mny;
    }

    // 计算商品总金额
    for (final goods in _selectListGoods) {
      // print('商品数量--> ${goods.count} 价格---> ${goods.price.formatYuan}');
      total += goods.getTotalPrice();
    }

    _totalOrderAmount.value = double.parse(total.toYuan);

    // 如果啥都没了 清空优惠
    if (_selectListOils.isEmpty && _selectListGoods.isEmpty) {
      setDiscountInfo(null);
    }
  }

  // reset
  void reset() {
    orderPollFinanceId = '';
    _selectListOils.clear();
    _selectListGoods.clear();
    _totalOrderAmount.value = 0.0;
    // selectPayType(null);
    logout();
  }

  // 清空优惠
  void clearDiscount() {
    setDiscountInfo(null);
    // 清空优惠券
    selectedCoupon.clear();
    // 清空优惠金额
    offLineDiscount.value = 0.0;
    mCardList.clear();
  }

  /// 获取员工列表
  void getEmployeeList({void Function(List<EmployeeEntity>)? success}) {
    asyncRequestNetwork<List<EmployeeEntity>>(
      isShow: false,
      Method.get,
      url: HttpApi.getEmployeeList,
      onSuccess: (list) {
        mAllListEmployee.assignAll(list ?? []);
        success?.call(list ?? []);
      },
    );
  }

  /// 获取当班员工列表
  void getEmployeeSelectList({required void Function(List<EmployeeEntity>) success}) {
    asyncRequestNetwork<List<EmployeeEntity>>(
      isShow: false,
      Method.post,
      url: HttpApi.getEmployeeSelectList,
      params: {
        'workCycleCode': CurrentShiftEntity.get()?.workCycleCode ?? '',
      },
      onSuccess: (list) {
        mSelectListEmployee.clear();
        mSelectListEmployee.addAll(list ?? []);
        success(mSelectListEmployee);
      },
    );
  }

  /// 保存选择的当班员工列表
  void saveSelectEmployeeList(List<EmployeeEntity> mList, {required void Function() success}) {
    asyncRequestNetwork<String>(Method.post, url: HttpApi.saveEmployeeSelect, params: {
      'workCycleCode': CurrentShiftEntity.get()?.workCycleCode ?? '',
      'mchUserIdList': mList.map((e) => e.userId).toList(),
    }, onSuccess: (data) {
      mSelectListEmployee.assignAll(mList);
      success();
    }, onError: (code, msg) {
      Toast.show(msg);
    });
  }

  // 请求预付款
  void requestAdvanceOrderStatisticsPage({
    bool isShow = false,
    int pageSize = 10,
    void Function(ListAdvancePrePayOrderEntity? data)? onSuccessCallBack,
  }) {
    requestNetwork<ListAdvancePrePayOrderEntity>(isShow: isShow, Method.post, url: HttpApi.getAdvanceOrderStatisticsPage, onSuccess: (data) {
      // 如果大于0 显示
      if ((data?.total ?? 0) > 0) {
        advanceOrderCount.value = '（${data?.total}）';
      } else {
        advanceOrderCount.value = '';
      }
      onSuccessCallBack?.call(data);
    }, params: {
      'pageNo': 1,
      'pageSize': pageSize,
      'shiftNo': CurrentShiftEntity.get()?.workCycleCode,
      'mchCode': GetUserInfoEntity.get()?.loginMerchantCode,
      'advanceOrder': 1,
      'orderStatusList': [1030],
    });
  }

  // 请求未支付的油单列表
  void requestUnPayOrderList({
    bool isShow = false,
    int pageSize = 100,
    void Function(ListAdvancePrePayOrderEntity? data)? onSuccessCallBack,
  }) {
    requestNetwork<ListAdvancePrePayOrderEntity>(isShow: isShow, Method.post, url: HttpApi.getUnpaidOrderList, onSuccess: (data) {
      onSuccessCallBack?.call(data);
    }, params: {
      'pageNo': 1,
      'pageSize': pageSize,
      'shiftNo': CurrentShiftEntity.get()?.workCycleCode,
      'mchCode': GetUserInfoEntity.get()?.loginMerchantCode,
      'energyOrderStatusList': [OrderOilStatus.WAIT_PAY, OrderOilStatus.LOCK],
    });
  }

  // 匹配订单
  void requestMtMatch({
    bool isShow = false,
    required List<String> orderIds,
    required List<String> energyOrderIds,
    required void Function() onSuccessCallBack,
    // required void Function() onErrorCallBack,
  }) {
    requestNetwork<String>(isShow: isShow, Method.post, url: HttpApi.mtMatch, onSuccess: (data) {
      onSuccessCallBack.call();
    }, onError: (code, msg) {
      Toast.show(msg);
      // onErrorCallBack.call();
    }, params: {
      'energyOrderIds': energyOrderIds,
      'orderIds': orderIds,
    });
  }

  // 解锁油单
  void requestUnlockOrder(String orderId, {required void Function() onSuccessCallBack}) {
    requestNetwork<String>(Method.get, isShow: true, url: HttpApi.unlockOrder.replaceAll('energyOrderId', orderId), onSuccess: (data) {
      Toast.show('解锁成功');
      onSuccessCallBack.call();
    }, params: {
      'orderId': orderId,
    });
  }
}
